package com.pms.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.pms.cache.utils.RedisCacheUtil;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.rpc.UserService;
import com.pms.service.ICameraUserInformationService;
import com.pms.service.IWaterPumpHouseService;
import com.pms.util.FluoriteCloudUtile;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import org.springframework.web.bind.annotation.*;
import com.pms.controller.BaseController;
import com.pms.service.IEqCameraService;
import com.pms.result.ObjectRestResponse;
import com.pms.result.TableResultResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "/pms/eqCamera")
@Api(value="App摄像头接口",description = "App摄像头接口")
public class EqCameraController extends BaseController {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ICameraUserInformationService service;
    @Autowired
    private IEqCameraService eqCameraService;
    @Autowired
    private IWaterPumpHouseService waterPumpHouseService;
    @Autowired
    private UserService userService;
    @Autowired
    private  RedisCacheUtil RedisCacheUtil;
    /**
     * 添加摄像头
     * @param key
     * @param verificationCode
     * @param place
     * @param waterPumpHouseId
     * @param userId
     * @return
     * @throws Exception
     */
    @RequestMapping("/add/camera")
    @ApiOperation("添加摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "设备序列号", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "verificationCode", value = "验证码", required = true, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "place", value = "摄像头位置", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "waterPumpHouseId", value = "水泵房ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "Long", paramType = "form")
    })
    public R addCamera(String key, String verificationCode, String place, Long waterPumpHouseId, Long userId) throws Exception {
        Assert.isNull(key,"序列号key不能为空");
        Assert.isNull(verificationCode,"验证码verificationCode不能为空");
        Assert.isNull(place,"摄像头名称place不能为空");
        Assert.isNull(waterPumpHouseId,"水泵房ID不能为空");
        Assert.isNull(userId,"用户ID不能为空");
        WaterPumpHouse waterPumpHouse= waterPumpHouseService.selectById(waterPumpHouseId);
        Assert.isNull(waterPumpHouse,"该水泵房信息不存在");
        BaseUserInfo user = userService.getUserByUserId(userId);
        Assert.isNull(user,"该用户信息不存在");
        EqCamera eq =new EqCamera();
        eq.setWaterPumpHouseId(waterPumpHouseId);//水泵房ID
        eq.setUserId(userId);//用户ID
        eq.setKey(key);//序列号
        eq.setVerificationCode(verificationCode);//验证码
        eq.setPlace(place);//位置
        eq.setRemack(place);//备注
        eq.setCreateBy(userId.toString());
        eq.setEquipmentId("1");//通道号默认为1
        eq.setCreateTime(new Date());//创建时间
        eq.setCurrentdateTime(new Date());//当前时间
        List<CameraUserInformation> camerauser = service.selectList(new EntityWrapper<CameraUserInformation>().lt("sum_",10));//查询所有摄像头sum不足10个
        if(camerauser.size()!=0||null!=camerauser ||!camerauser.isEmpty()){
            eq.setCameraUserId(camerauser.get(0).getId());
            CameraUserInformation cu=service.selectById(camerauser.get(0).getId());
            JSONObject json = FluoriteCloudUtile.fluoriteCloud1(cu.getAppkey(),cu.getAppsecret());
            String code = json.getString("code");
            if(code.equals("200")){
                String data = json.getString("data");
                if(StringUtils.isNotEmpty(data)){
                    JSONObject jsonResult = JSON.parseObject(data);
                    String accessToken = jsonResult.getString("accessToken");//token码
                    String expireTime = jsonResult.getString("expireTime");//结束时间
                    eq.setToken(accessToken);//保存token码
                    try{
                        SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Long time=new Long(expireTime);
                        String d = format.format(time);//时间戳转换成标准时间
                        Date  e = format.parse(d);     //标准时间转换成国际时间
                        Calendar cal = Calendar.getInstance();//使用默认时区和语言环境获得一个日历
                        cal.setTime(e);
                        cal.add(Calendar.DATE, -1);  //结束时间减1天
                        eq.setExpireTime(format.parse(format.format(cal.getTime())));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            JSONObject cloud =new JSONObject();
            cloud = FluoriteCloudUtile.addfluoriteCloud(eq.getKey(), eq.getVerificationCode(),eq.getToken());
            String code1=cloud.getString("code");
            if(code1.equals("200")){
                JSONObject capture = FluoriteCloudUtile.capture(eq.getKey(),"1",eq.getToken());
                if(capture.getString("code").equals("200")){
                    JSONObject data= capture.getJSONObject("data");
                    Object img=data.get("picUrl");
                    eq.setPicurl(img.toString());
                    RedisCacheUtil.saveAndUpdate("PhotoCapture"+eq.getId(), img,10);
                }
                eqCameraService.insert(eq);
                cu.setSum(cu.getSum()+1);
                service.updateAllColumnById(cu);//修改总数
                return R.ok();
            }else{
                throw new RRException(cloud.toJSONString());
            }
        }else{
            throw new RRException("对不起没有可用用户配置信息，请联系管理员",400);
        }
    }

    /**
     * 修改摄像头
     * @param id
     * @return
     */
    @RequestMapping("/update")
    @ApiOperation(value = "修改摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "摄像头ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "place", value = "摄像头位置", required = false, dataType = "String", paramType = "form"),
            @ApiImplicitParam(name = "waterPumpHouseId", value = "水泵房ID", required = true, dataType = "Long", paramType = "form"),
    })
    public R update(Long id,Long waterPumpHouseId,String place){
        Assert.isNull(place,"摄像头名称place不能为空");
        Assert.isNull(waterPumpHouseId,"水泵房ID不能为空");
        Assert.isNull(id," 设备ID不能为空");
        EqCamera eqCamera=eqCameraService.selectById(id);
        Assert.isNull(eqCamera," 该摄像头信息不存在");
        if (StringUtils.isNotEmpty(place)){
            eqCamera.setPlace(place);
        }
        if (waterPumpHouseId==null){
            eqCamera.setWaterPumpHouseId(waterPumpHouseId);
        }
        eqCameraService.updateById(eqCamera);
        return R.ok();

    }

    /**
     * 删除摄像头
     * @param id  摄像头ID
     * @return
     */
    @RequestMapping("/delete")
    @ApiOperation(value = "删除摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "摄像头ID", required = true, dataType = "Long", paramType = "form"),
    })
    public R delete(Long id){
        Assert.isNull(id," 设备ID不能为空");
        EqCamera eqCamera=eqCameraService.selectById(id);
        Assert.isNull(eqCamera," 该摄像头信息不存在");
        JSONObject cloud = FluoriteCloudUtile.deletefluoriteCloud(eqCamera.getKey(),eqCamera.getToken());
        if(cloud.getString("code").equals("200")){
            CameraUserInformation user=service.selectById(eqCamera.getCameraUserId());
            Assert.isNull(user,"该摄像头用户配置信息不存在");
            user.setSum(user.getSum()-1);
            service.updateAllColumnById(user);
            eqCameraService.deleteById(eqCamera.getId());
            return R.ok();
        }else{
            throw new RRException(cloud.toJSONString());
        }
    }


    /**
     * findByID
     * @param id
     * @return
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ObjectRestResponse<EqCamera> findById(@PathVariable int id){
        return new ObjectRestResponse<EqCamera>().rel(true).data( eqCameraService.selectById(id));
    }

    /**
     * 分页查询摄像头
     * @param limit
     * @param page
     * @param place
     * @return
     */
    @RequestMapping(value = "/page",method = RequestMethod.POST)
    public TableResultResponse<EqCamera> page(Integer limit, Integer page, String place,Long userId){
        if (limit==null){limit=10;}
        if (page==null){page=1;}
        BaseUserInfo baseUserInfo = userService.getUserByUserId(userId);
        Assert.isNull(baseUserInfo,"没有此用户");
        Page<EqCamera> pages = new Page<EqCamera>(page,limit);
        Wrapper<EqCamera> ew=new EntityWrapper<EqCamera>();
        ew.like("place_",place);
        if (baseUserInfo.getType()==4){//物业查询当前自己添加的摄像头
            ew.eq("user_id",userId);
            pages = eqCameraService.selectPage(pages,ew);
        }else if (baseUserInfo.getType()==1){//平台查询所有摄像头
            pages = eqCameraService.selectPage(pages,ew);
        }
        if (pages==null){
            return new TableResultResponse<EqCamera>();
        }else{
            return new TableResultResponse<EqCamera>(pages.getTotal(),pages.getRecords());
        }
    }


}